<template>
  <div id="questionnaire-list">
    <a-table
      :columns="columns"
      :row-key="record => record.id"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
    >
      <template slot="action" slot-scope="record"> 
        <a @click="() => handlePreview(record)">预览</a>
        <a-divider type="vertical" />
        <a @click="() => handlePubilish(record)">发布</a>
        <a-divider type="vertical" />
        <a class="ant-dropdown-link" @click="() => handleDel(record)">删除</a>
      </template>
    </a-table>

    <!-- 预览弹出框 -->
    <a-modal 
      :visible="modelVisible"
      title="模板预览" 
      destroyOnClose
      width="700px"
      cancelText="iphone版"
      okText="pc版"
      @cancel="modelCancel"
    >
      <q-preview :templateData="templateData" :isPc="isPc"></q-preview>
      <template slot="footer">
        <a-button key="back" @click="showPcStyle" :class="isActive ? 'active' : null">
          pc版
        </a-button>
        <a-button key="submit" @click="showPhoneStyle">
          iphone版
        </a-button>
      </template>
    </a-modal>

    <!-- 生成二维码 -->
    <a-modal 
      v-model="qrCodeVisible" 
      title="二维码"
      :footer="null" 
      destroyOnClose
    >
      <div class="qrcode">
        <div class="url-copy"><input v-model="url" class="url" ref="url-copy"/><a-button class="copy" @click="copyUrl2">复制</a-button></div>
        <div id="qrcode" ref="qrcode"></div>
      </div>
    </a-modal>
  </div>
</template>
<script>
// import reqwest from 'reqwest';
import Api from '@/services/commonApi'
import Preview from './components/preview'
import QRCode from 'qrcodejs2'
import clip from '@/utils/clipboard'
const columns = [
  {
    title: '模板标题',
    dataIndex: 'titleName',
    sorter: true,
    width: '20%',
  },
  {
    title: '模板描述',
    dataIndex: 'headline',
    // ellipsis: true,
    // width: '20%',
  },
  {
    title: '模板状态',
    dataIndex: 'status',
    filters: [
      { text: '发布', value: 1 },
      { text: '未发布', value: 0 },
    ],
    width: 200
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];

export default {
  data() {
    return {
      url: '',
      qrCodeVisible: false,
      data: [],
      pagination: {
        pageSize: 10,
        current: 1
      },
      loading: false,
      columns,
      modelVisible:  false,
      isPc: true,
      templateData: {},
      isActive: true,
    };
  },
  mounted() {
    this.fetch();
  },
  components: {
    'q-preview': Preview
  },
  methods: {
    

    /**
     * @Description: 预览
     * @param {*}
     * @Date: 2020-11-02 13:27:42
     */    
    handlePreview(val) {
      this.modelVisible = true
      this.templateData = val
    },

    /**
     * @Description: 预览关闭
     * @param {*}
     * @Date: 2020-11-02 13:27:48
     */    
    modelCancel() {
      this.modelVisible = false
    },

    /**
     * @Description: 预览pc版
     * @param {*}
     * @Date: 2020-11-02 13:27:56
     */    
    showPcStyle() {
      this.isPc = true
    },

    /**
     * @Description: 预览手机版
     * @param {*}
     * @Date: 2020-11-02 13:28:10
     */    
    showPhoneStyle() {
      this.isPc = false
      this.isActive = false
    },

    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.fetch({
        results: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      });
    },
    fetch() {
      this.loading = true;
      Api.post('app/center/inner/template/pageTemplate', {
        "size": this.pagination.pageSize,
        "current": this.pagination.current
      })
      .then(data => {
        const pagination = { ...this.pagination };

        // Read total count from server
        // pagination.total = data.totalCount;
        // pagination.total = data.data.count;
        this.loading = false;
        if(!data.data.data.templateVos.length) {
          return this.data = []
        }
        this.data = data.data.data.templateVos.map(item => {
          item.status === 0 ? item.status = '已发布' : item.status ='未发布'
          return item
        });
        this.pagination = pagination;
      });
    },

    /**
     * @Description: 删除模板接口
     * @param {*}
     * @Date: 2020-11-02 10:49:14
     */    
    handleDel(val) {
      this.$confirm({
        title: '你确定要删除这个模板吗?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          Api.del('app/center/inner/template/delTemplate', val.id).then(() => {
            this.$message.success('删除成功！')
            this.fetch();
          }).catch(() => {
            this.$message.error('删除失败，请重试！')
          })
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @Description: 发布逻辑
     * @param {*}
     * @Date: 2020-11-02 13:28:50
     */    
    handlePubilish(val) {
      this.url = `${window.location.origin}/#/preview?id=${val.id}`
      this.payOrder();
      // this.$router.push({path: '/perview', query: {id: 32}})
    },

    /**
     * @Description: 展示二维码
     * @param {*}
     * @Date: 2020-11-02 14:42:49
     */    
    payOrder () {
      this.qrCodeVisible = true
      // 使用$nextTick确保数据渲染
      this.$nextTick(() => {
        this.crateQrcode()
      })
    },

    /**
     * @Description: 生成二维码
     * @param {*}
     * @Date: 2020-11-02 14:43:15
     */    
    crateQrcode () {
      this.qr = new QRCode('qrcode', {
        width: 150,
        height: 150, // 高度
        text: this.url // 二维码内容
        // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        // background: '#f0f'
        // foreground: '#ff0'
      })
    },

    /**
     * @Description: 复制链接
     * @param {*}
     * @Date: 2020-11-02 15:04:14
     */    
    copyUrl2(event) {
      // var urlDom= this.$refs['url-copy'];
      // console.log('Url2', urlDom)
      // urlDom.select(); // 选择对象
      // document.execCommand("Copy");
      // // window.clipboardData.setData("Text",this.url);
      // this.$message.success('已复制！')
      clip(this.url, event)
    }
  },
};
</script>

<style lang="less">
  .active {
    color: #13c2c2;
    // background-color: #fff;
    border-color: #13c2c2;
  }
  .qrcode {
      display: flex;
      flex-direction: column;
      align-items: center;
      .url-copy {
        height: 40px;
        display: flex;
        margin-bottom: 20px;
        .url {
          width: 350px;
          // background-color: #eee;
          line-height: 40px;
          border: 1px solid #d9d9d9;
          border-right: none;
          border-width: 1px;
          padding-right: 10px;
          padding-left: 10px;
        }
        .copy {
          height: 40px;
          width: 80px;
          // background-color: chartreuse;
          border-radius: 0;
        }
      }
    }
  #questionnaire-list {
    background-color: #fff;
    padding: 20px;
    
  }
</style>
